﻿using System.Threading.Tasks;
using System.Web.Mvc;
using Systematize.Domain.Entities;
using Systematize.Domain.Services;
using Systematize.Models.Library;

namespace Systematize.Controllers
{
    public class LibraryController : Controller
    {
        private readonly ILibraryItemServiceAsync<Book> _bookService;

        public LibraryController(ILibraryItemServiceAsync<Book> bookService)
        {
            _bookService = bookService;
        }

        public ActionResult Index()
        {
            var model = new IndexModel
            {
                CategoryName = "Books",
                LibraryItems = _bookService.GetAll()
            };
            return View(model);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public async Task<ActionResult> Create(EditModel model)
        {
            if (!ModelState.IsValid) return View(model);

            var book = new Book
            {
                Name = model.Name,
                Description = model.Description,
                Price = model.Price,
                Rating = model.Rating
            };
            await _bookService.CreateAsync(book);
            return RedirectToAction("Edit", new { id = book.Id });
        }

        public async Task<ActionResult> Edit(int id)
        {
            Book book = await _bookService.GetByIdAsync(id);
            var model = new EditModel
            {
                Id = id,
                Name = book.Name,
                Description = book.Description,
                Price = book.Price,
                Rating = book.Rating,
                CreatedOn = book.CreatedOn
            };
            return View(model);
        }

        [HttpPost]
        public async Task<ActionResult> Edit(EditModel model)
        {
            if (!ModelState.IsValid) return View(model);

            Book existingBook = await _bookService.GetByIdAsync(model.Id);
            existingBook.Name = model.Name;
            existingBook.Description = model.Description;
            existingBook.Price = model.Price;
            existingBook.Rating = model.Rating;

            await _bookService.UpdateAsync(existingBook);
            return RedirectToAction("Index");
        }
    }
}